package com.gitee.wsl.coroutines.strategy

//package com.lzx.starrysky.utils


import com.gitee.wsl.ext.base.*
import com.gitee.wsl.service.task.scope.DelayRunScope


inline fun twiceCheckDelayCallBack(lastBackTime: Long,
                                   delayMillis: Long = 2000,
                                   onFirstBackPressed: () -> Unit={},
                                   finish:()->Unit):Long{
    val currentTime = currentTimeMillis
    if (currentTime - lastBackTime > delayMillis) {
        onFirstBackPressed()
        return currentTime
    } else {
        finish()
    }
    return lastBackTime
}

inline fun onlyOneCheckDelayCallBack(lastBackTime: Long,
                                  delayMillis: Long =800,
                                  onFirstBackPressed: () -> Unit={}):Long{
    val currentTime = currentTimeMillis
    if (currentTime - lastBackTime > delayMillis) {
        onFirstBackPressed()
        return currentTime
    }
    return lastBackTime
}

class OnlyOneRun (
    val delayMillis: Long = 800,
    var onFirstBackPressed: () -> Unit={}
){
    var lastBackTime: Long = 0

    fun call(){
        lastBackTime = onlyOneCheckDelayCallBack(lastBackTime, delayMillis ,onFirstBackPressed )
    }
}

class DelayTwiceRun(val delayMillis: Long = 2000,
                    var onFirstBackPressed: () -> Unit={},
                    var finish:()->Unit){
    var lastBackTime: Long = 0

    fun call(){
        val currentTime = currentTimeMillis
        if (currentTime - lastBackTime > delayMillis) {
            lastBackTime = currentTime
            onFirstBackPressed()
        } else {
            finish()
        }
    }

    companion object{

        fun build(delayMillis: Long = 2000,config: DelayRunScope.()->Unit):DelayTwiceRun{
            val delayTwiceRun=DelayTwiceRun(delayMillis, finish = {} )
            val scope=object : DelayRunScope {
                override fun onFirstPressed(callback: () -> Unit) {
                    delayTwiceRun.onFirstBackPressed=callback
                }

                override fun onFinish(callback: () -> Unit) {
                   delayTwiceRun.finish=callback
                }

                override fun cancel() {
                    delayTwiceRun.lastBackTime = 0
                }

            }
            config(scope)

            return delayTwiceRun
        }
    }
}


